<template>
  <Menu
    ref="menuRef"
    class="basic-menu"
    :selected-keys="[activeMenuPath]"
    :open-keys="expandedMenuIndexes"
    :collapsed="collapsed"
    @openChange="onMenuOpen"
    :mode="menuMode"
    collapsible
  >
    <template v-for="item in items" :key="item.path">
      <MenuItem
        v-if="!item.meta || !item.meta.hidden"
        :item="item"
        :base-path="resolveFullPath(item.path)"
      />
    </template>
  </Menu>
</template>

<script setup>
import { Menu } from 'ant-design-vue'
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import path from 'path-browserify'
import MenuItem from './components/MenuItem.vue'
import { isExternal } from '@/utils/index'
defineOptions({
  name: 'BasicMenu',
})
const props = defineProps({
  items: {
    type: Array,
    default: () => [],
  },
  collapsed: {
    type: Boolean,
    default: false,
  },
  menuMode: {
    type: String,
    default: 'inline',
    validator: (value) => ['inline', 'horizontal'].includes(value),
  },
})
const menuRef = ref()
const currentRoute = useRoute()
const expandedMenuIndexes = ref([])

// 计算当前激活的菜单项
const activeMenuPath = computed(() => {
  const { meta, path } = currentRoute

  // 如果路由meta中设置了activeMenu，则使用它（用于处理一些特殊情况，如详情页）
  if (meta?.activeMenu && typeof meta.activeMenu === 'string') {
    return meta.activeMenu
  }

  // 否则使用当前路由路径
  return path
})

/**
 * 获取完整路径
 *
 * @param routePath 当前路由的相对路径  /user
 * @returns 完整的绝对路径
 */
function resolveFullPath(routePath) {
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(props.basePath)) {
    return props.basePath
  }

  // 如果 basePath 为空（顶部布局），直接返回 routePath
  if (!props.basePath || props.basePath === '') {
    return routePath
  }

  // 解析路径，生成完整的绝对路径
  return path.resolve(props.basePath, routePath)
}

/**
 * 打开或关闭菜单
 *
 * @param openKeys
 */
const onMenuOpen = (openKeys) => {
  expandedMenuIndexes.value = openKeys
}
</script>

<style lang="scss" scoped></style>
